1691E - Number of Groups - CodeForces Solution


data structures dfs and similar dsu graphs greedy sortings *2300

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>

using namespace std;

using ll = long long;
typedef pair<int,int> PII;

struct DSU{
    vector<int> dsu, szx;

    DSU() = default;
    DSU(int n) : dsu(n), szx(n, 1) {
        for (int i = 0; i < n; i ++ ) dsu[i] = i;
    }

    int parent(int i){
        if (dsu[i] == i) return i;
        else return dsu[i] = parent(dsu[i]);
    }

    int size(int i) { return szx[parent(i)]; }
    int operator[](int i) { return parent(i); }
    int num_count(){
        int cnt = 0;
        for (int i = 0; i < dsu.size(); i ++ ) if (dsu[i] == i) cnt ++ ;
        return cnt;
    }

    void unify(int a, int b){
        a = parent(a);
        b = parent(b);
        if (szx[a] < szx[b]) swap(a, b);
        if (a != b) dsu[b] = a, szx[a] += szx[b];
    }
};

struct Point{
    int t, p, pc, id;
    bool close;
    bool operator<(Point &other){
        if (p == other.p) return close < other.close;
        return p < other.p;
    }
};

void solve()
{
    int n; cin >> n;
    vector<Point> points;
    for (int i = 0; i < n; i ++ ){
        int t, l, r; cin >> t >> l >> r;
        points.push_back({t, l, r, i, false});
        points.push_back({t, r, l, i, true});
    }
    sort(points.begin(), points.end());

    DSU dsu(n);
    vector<set<PII>> open(2);
    for (auto &p : points){
        if (p.close) open[p.t].erase({p.p, p.id});
        else {
            open[p.t].insert({p.pc, p.id});
            while (open[p.t ^ 1].size() > 1){
                auto [r, id] = *open[p.t ^ 1].begin();
                dsu.unify(p.id, id);
                open[p.t ^ 1].erase({r, id});
            }
            if (open[p.t ^ 1].size() == 1) dsu.unify(p.id, open[p.t ^ 1].begin()->second);
        }
    }
    cout << dsu.num_count() << endl;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);

    int _T; cin >> _T;
    while (_T -- ) solve();

    return 0;
}


Comments

Submit
0 Comments
More Questions

231A - Team
479C - Exams
1030A - In Search of an Easy Problem
158A - Next Round
71A - Way Too Long Words
160A - Twins
1A - Theatre Square
1614B - Divan and a New Project
791A - Bear and Big Brother
1452A - Robot Program
344A - Magnets
96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters
1478B - Nezzar and Lucky Number
228A - Is your horseshoe on the other hoof
122A - Lucky Division
1611C - Polycarp Recovers the Permutation
432A - Choosing Teams
758A - Holiday Of Equality
1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD
149A - Business trip
34A - Reconnaissance 2
59A - Word